// -----------------------------------------------跟随要用的地方走----------------------------------------------

// moment获取时间
const moment = require('moment');

// 连接数据库
const conn = require('../db/db.js');

// 引入加密
const bscryptjs = require('bcryptjs');

// -----------------------------------------------后台操作----------------------------------------------

const showRegister=(req,res) => {
    res.render('./user/register.ejs',{});
};

const showLogin=(req,res) => {
    res.render('./user/login.ejs',{});
}

const Register=(req,res) => {
    let user = req.body;
    let mi = 10;
    user.ctime = moment().format('YYYY-MM-DD HH:mm:ss');
    // 查询用户名是否已经存在
    let sql1 = 'select count(*) as count from blog_users where username = ?';
    conn.query(sql1,user.username,(err,result) => {
        if(err) return res.send({status:501,msg:'查询失败' + err.message});
        if(result[0].count != 0) return res.send({status:502,msg:'用户名重复'});
        // 给密码加密
        bscryptjs.hash(user.password,mi,(err,pwd) => {
            // console.log(pwd)
            user.password = pwd;
            let sql2 = 'insert into blog_users set ?';
            conn.query(sql2,user,(err,result) => {
                if(err) return res.send({status:503,msg:'注册失败' + err.message});
                res.send({status:200,msg:'success'});
            });
        });
        
    });
}

const Login=(req,res) => {
    let user = req.body;
    if(user.username.trim() == '' || user.password.trim() == '') {
        res.send({status:500,msg:"用户名密码不能为空"});
    }
    let sql = 'select * from blog_users where username = ?';
    conn.query(sql,user.username,(err,result) => {
        if(err) return res.send({status:501,msg:'查询失败' + err.message});
        if(result.length == 0) return res.send({status:502,msg:"用户密码不存在"});
        // 解密 密码相同为true
        bscryptjs.compare(user.password,result[0].password,(err,jg) => {
            console.log(jg)
            if(!jg) return res.send({status:502,msg:'密码错误'});
            // 将登录的用户信息和islogin存入到session中
            req.session.user = result[0];
            req.session.islogin = true;
            // 成功输出
            res.send({status:200,msg:"success"});
        });
    });
}

const Logout = (req,res) => {
    // 删除session 并跳转到主页面
    req.session.destroy(() => {
        // 重新跳转到指定页面
        res.redirect('/');
    });
    
}

module.exports = {
    showRegister,
    showLogin,
    Register,
    Login,
    Logout
}